package com.easyattendance.services;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Subject;
import com.easyattendance.model.TimeSlot;
import com.easyattendance.model.TimeTable;
import com.easyattendance.util.HibernateUtil;

public class TimeTableService {

	/* Method to CREATE a timetable in the database */
	   public synchronized boolean addTimeTable(TimeTable timeTable){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	     
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.save(timeTable);
	           	 tx.commit();

	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return true;
	   }
	   
	   public boolean ifAlreadyExists(TimeTable timeTable) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List timeTables = null;
		      try{
		         tx = session.beginTransaction();
		         timeTables = session.createQuery("FROM TimeTable").list(); 
		         for (Iterator iterator = timeTables.iterator(); iterator.hasNext();){
		        	 TimeTable temp = (TimeTable) iterator.next(); 
		            if(temp.equals(timeTable)) {
		            	System.out.println("time table already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	   String[] calcTimeSlots(Date tmpTime, Date lastLecTime, TimeSlot timeSlotObj, String[] timeSlot) {
			
			int i = 0;
			while (tmpTime.compareTo(lastLecTime) <= 0) {
				if (tmpTime.compareTo(timeSlotObj.getRecess1_time()) == 0) {
					tmpTime.setMinutes(tmpTime.getMinutes() + timeSlotObj.getRecess1_minutes());
				}
				else if (tmpTime.compareTo(timeSlotObj.getRecess2_time()) == 0 ){
					tmpTime.setMinutes(tmpTime.getMinutes() + timeSlotObj.getRecess2_minutes());
				}
				else {
					tmpTime.setMinutes(tmpTime.getMinutes() + timeSlotObj.getLecture_minutes());
				}
				timeSlot[++i] = tmpTime.getHours() + ":" + tmpTime.getMinutes();
			}
			return timeSlot;
	   }
	   
	   public String[] getDaysHeader() {
		   String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
		   /*Map<String,String> daysMap = new HashMap<String, String>();
			for (int i = 0; i < days.length; i++) {
				daysMap.put(days[i], days[i]);
			}*/
		   return days;
	   }
	   
	public String[] getTimeSlotsMap(String sectionId) {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		//Map<String, String> timeSlotsMap = new HashMap<String, String>();
		String[] timeSlot = new String[10];

		try {
			tx = session.beginTransaction();
			List TimeTableSlots = session.createQuery("FROM TimeSlot WHERE section_id='" + sectionId + "'").list();

			for (Iterator iterator = TimeTableSlots.iterator(); iterator.hasNext();) {
				TimeSlot timeTableSlot = (TimeSlot) iterator.next();
				// initTimeTableSlot(timeTableSlot);
				int lecture_minutes = timeTableSlot.getLecture_minutes();
				Date start_time = timeTableSlot.getStart_time();
				Date end_time = timeTableSlot.getEnd_time();

				int totalSchoolTime = (end_time.getHours() - start_time.getHours());

				Date lastLecTimeDt = null;
				Date tmpTime = null;
				// Calculate last lecture time and tmpTime
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					lastLecTimeDt = format.parse(end_time.toString());
					lastLecTimeDt.setMinutes(lastLecTimeDt.getMinutes() - lecture_minutes);

					tmpTime = format.parse(start_time.toString());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				
				timeSlot[0] = start_time.getHours() + ":" + start_time.getMinutes();
				timeSlot = calcTimeSlots(tmpTime, lastLecTimeDt, timeTableSlot,	timeSlot);

				/*for (int i = 0; i < 9; i++) {
					timeSlotsMap.put(timeSlot[i], timeSlot[i]);
				}*/

			}
			tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return timeSlot;
	}
	
	
	public String[][] getTeacherWiseSubjects(String[] timeSlots, String emailId) {
		String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
		String[][] subjects= new String[10][];
		
		AddTeacherService teacherService = new AddTeacherService();
		String teacherId = teacherService.getTeacherByEmailId(emailId).getTeacher_id();
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		
		try {
			tx = session.beginTransaction();
			
			for(int i=0; i<days.length; i++) {
				subjects[i] = new String[9];
				String tmpTime = null;
			
			for(int t=0; t<timeSlots.length - 1; t++) {
					tmpTime = "2013-10-10 "+timeSlots[t]+":00";
					SQLQuery query = session.createSQLQuery("SELECT TT.subject_id FROM TBL_TimeTable as TT, TBL_Teacher as teacher, TBL_Subject_Teacher as subjectT"
							+ " WHERE TT.day_of_week='" + days[i] + "' and TT.time_slot='"+tmpTime+"' "
							+ "and subjectT.subject_id = TT.subject_id and subjectT.teacher_id='"+teacherId+"' "
									+ "and subjectT.teacher_id = teacher.teacher_id and TT.teacher_id=subjectT.teacher_id");
					
					/*Query query = session.createQuery("SELECT TT.subject_id FROM TimeTable as TT "
							+ " WHERE TT.dayOfWeek='" + days[i] + "' and TT.time_slot='"+tmpTime+"' "
									+ "and subject.subject_id = TT.subject_id and teacher.teacher_id='"+emailId+"' "
								+ "and subject.teacher_id = teacher.teacher_id");*/
					
						
					subjects[i][t] = (String) query.uniqueResult();
					System.out.println("Teacher subject: "+subjects[i][t]);
					
					   
					
			}
		}
		
		tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return subjects;
		}
	
	public String[][] getTeacherWisetimeSlots(String[] timeSlots, String emailId) {
		String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
		String[][] subjects= new String[10][];
		AddTeacherService teacherService = new AddTeacherService();
		String teacherId = teacherService.getTeacherByEmailId(emailId).getTeacher_id();
		
		Session session = HibernateUtil.openSession();
		Transaction tx = null;

		try {
			tx = session.beginTransaction();
			
			for(int i=0; i<days.length; i++) {
				subjects[i] = new String[9];
				String tmpTime = null;
				Date tmpSlot=null;
			
			for(int t=0; t<timeSlots.length - 1; t++) {
					tmpTime = "2013-10-10 "+timeSlots[t]+":00";
					
					/*List list = session.createSQLQuery("SELECT TT.time_slot FROM TBL_TimeTable as TT, TBL_Teacher as teacher, TBL_Subject_Teacher as subjectT"
							+ " WHERE TT.day_of_week='" + days[i] + "' and TT.time_slot='"+tmpTime+"' "
							+ "and subjectT.subject_id = TT.subject_id and subjectT.teacher_id='"+teacherId+"' "
									+ "and subjectT.teacher_id = teacher.teacher_id").list();
					
					for(Iterator itr = list.iterator(); itr.hasNext(); ) {
						System.out.println(":::Time Slot::::"+ ((Date)itr.next()).getTime_slot().toString());
					}*/
					SQLQuery query = session.createSQLQuery("SELECT TT.time_slot FROM TBL_TimeTable as TT, TBL_Teacher as teacher, TBL_Subject_Teacher as subjectT"
							+ " WHERE TT.day_of_week='" + days[i] + "' and TT.time_slot='"+tmpTime+"' "
							+ "and subjectT.subject_id = TT.subject_id and subjectT.teacher_id='"+teacherId+"' "
									+ "and subjectT.teacher_id = teacher.teacher_id");
					
					/*Query query = session.createQuery("SELECT TT.subject_id FROM TimeTable as TT "
							+ " WHERE TT.dayOfWeek='" + days[i] + "' and TT.time_slot='"+tmpTime+"' "
									+ "and subject.subject_id = TT.subject_id and teacher.teacher_id='"+emailId+"' "
											+ "and subject.teacher_id = teacher.teacher_id");*/
					if(query.uniqueResult() != null) {
						tmpSlot =  (Date) query.uniqueResult();
						subjects[i][t] = tmpSlot.toString();
					}
					else {
						tmpSlot = null;
						subjects[i][t] = null;
					}
					
					System.out.println("subject: "+subjects[i][t]);
			}
		}
		
		tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return subjects;
		}
	
	/*  get day and timeslot wise subject*/
	public String getSubject(String timeSlot, String day, String classId) {
		String tmpTime = null;
		String subject = null;
		TimeTable TT = null;
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		try {
			tx = session.beginTransaction();
			tmpTime = "2013-10-10 "+timeSlot+":00";
			Query query = session.createQuery("FROM TimeTable TT WHERE day_of_week='" + day + "' and time_slot='"+tmpTime+"' "
						+ "and class_id='"+classId+"'");
			TT = (TimeTable) query.uniqueResult();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		if(TT == null) {
			return "Free Lecture";
		}
		else {
			return TT.getSubject_id();
		}
	}
	
	/*  get day and timeslot wise teacher*/
	public String getTeacher(String timeSlot, String day, String classId) {
		String tmpTime = null;
		String teacher = null;
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		try {
			tx = session.beginTransaction();
			tmpTime = "2013-10-10 "+timeSlot+":00";
		
				Query query = session.createQuery("SELECT TT.teacher_id FROM TimeTable TT WHERE day_of_week='" + day + "' and time_slot='"+tmpTime+"' "
						+ "and class_id='"+classId+"'");
				teacher = (String) query.uniqueResult();
				tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return teacher;
		}
	
	/*  get no of teacher lectures for a day*/
	public int getTotalTeacherLecturesPerDay(String day, String teacherId) {
		String tmpTime = null;
		String teacher = null;
		int noOfLectures = -1;
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		
		try {
			tx = session.beginTransaction();
		
			List<TimeTable> tt = session.createQuery("FROM TimeTable TT WHERE day_of_week='" + day + "' and teacher_id='"+teacherId+"'").list();
			noOfLectures = tt.size();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		System.out.println("\n========\n teacher lec no: "+noOfLectures+"\n======\n");
		return noOfLectures;
		}
}
